package com.yulongtian.interviewWorks.day20220825;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.cn/problems/linked-list-cycle-lcci
 * @author YulongTian
 * @date 2022/8/25 - 14:50
 */
public class Test03 {
    public static void main(String[] args) {

    }

    public ListNode detectCycle(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode p1 = head;
        ListNode p2 = head;

        while (true) {
            p1=p1.next;
            if(p2.next!=null){
                p2=p2.next.next;
            }else {
                p2= null;
            }
            if (p1 == null || p2 == null) {
                break;
            }
            if(p1==p2){
                break;
            }
        }
        if(p1==null||p2==null){
            return null;
        }

        List<ListNode> listNodes=new ArrayList<>();
        listNodes.add(p1);
        p1=p1.next;
        while (p1!=p2){
            listNodes.add(p1);
            p1=p1.next;
        }

        p1=head;
        while (true){
            if(listNodes.contains(p1)){
                return p1;
            }else {
                p1=p1.next;
            }
        }
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
